<?php
// +----------------------------------------------------------------------
// | ITKEE [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017 http://www.itkee.cn.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: SuperMan <superman@itkee.cn>
// +----------------------------------------------------------------------
// | 站点父类控制器
// +----------------------------------------------------------------------
namespace app\common\controller;

use app\common\model\Identity;
use service\FileService;
use think\Controller;
use think\Cache;

/**
 * 站点父类控制器
 * Class AdminBase
 * @package app\common\controller
 */
class BaseController extends Controller
{
    public $type = '';
    protected function _initialize()
    {
        parent::_initialize();
        if(!is_file('./static/install.lock')){
            $this->redirect('install/index/index');
            die;
        }
        $this->type = $this->request->param('type','','trim');
        $this->assign('type',$this->type);

    }

    public function upload(){
        $ext = implode(',',explode(',',$this->request->post('ext')));
        $file = $this->request->file('file');
        list($path) = str_split( md5(date('Ymd')) , 16);
        $filepath = 'static' . DS . 'upload' . DS . $path;
        // 上传验证
        $validate = [];
        if($ext){
            $validate['ext'] = $ext;
        }
        $file->validate($validate);

        // 文件上传处理
        if (($info = $file->rule('uniqid')->move($filepath))) {
           $path =  self::getBaseUriLocal($path) .$info->getFilename();
           return json(['code' => 1 , 'msg' => '上传成功', 'data' => $path]);
        }else{
            // 上传失败获取错误信息
            return json(['code' => 0 , 'msg' =>  $file->getError()]);
        }
    }

    /**
     * 获取服务器URL前缀
     * @return string
     */
    public static function getBaseUriLocal($path){
        $base = request()->root();
        $root = strpos($base, '.') ? ltrim(dirname($base), DS) : $base;
        if ('' != $root) {
            $root = '/' . ltrim($root, '/');
        }
        return  "{$root}/static/upload/" . $path . '/';
    }
}